package com.single;

import java.lang.reflect.Constructor;

/**
 * 懒汉式单例模式
 */
public class LazyMan {

    private LazyMan() {
        synchronized (LazyMan.class) {
            if (lazyMan != null) {
                throw new RuntimeException("不要试图通过反射破坏");
            }
        }
    }

    private static LazyMan lazyMan;

    public static LazyMan getInstance() {

        //双重锁
        if (lazyMan == null) {
            synchronized (LazyMan.class) {
                if (lazyMan == null) {
                    lazyMan = new LazyMan();  //不是一个原子操作
                }
            }
        }
        return lazyMan;
    }

    public static void main(String[] args) throws Exception {

        LazyMan instance1 = LazyMan.getInstance();
        Constructor<LazyMan> declaredConstructor = LazyMan.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);  //无视私有的构造器
        LazyMan instance2 = declaredConstructor.newInstance();

        System.out.println(instance1);
        System.out.println(instance2);
    }
}
